//
//  VideoCommandView.m
//  ijkPlayer
//
//  Created by apple on 2018/5/13.
//  Copyright © 2018年 锦. All rights reserved.
//
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#import "VideoCommandView.h"
#import "CustomSlider.h"
/**
 速率
 */
typedef NS_ENUM(NSInteger,RateState) {
    slow_rate = 0,
    normal_rate ,
    fast_rate   ,
    fastest_rate
};

@interface VideoCommandView()<BrightnessViewDelegate,CustomSliderDelegate>
/**
 播放按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *playButton;
/**
 当前时间
 */
@property (weak, nonatomic) IBOutlet UILabel *currentTimeLabel;

/**
 视频总时长
 */
@property (weak, nonatomic) IBOutlet UILabel *totalTimeLabel;
/**
 速率
 */
@property (weak, nonatomic) IBOutlet UIButton *rateButton;
@property (assign, nonatomic) RateState rateState;
/**
 下，右，上View
 */
@property (weak, nonatomic) IBOutlet UIView *bottomToolView;
@property (weak, nonatomic) IBOutlet UIView *topToolView;
@property (weak, nonatomic) IBOutlet UIView *rightToolView;
/**
 显示快进快退值
 */
@property (weak, nonatomic) IBOutlet UIView *sheduleView;
@property (weak, nonatomic) IBOutlet UILabel *sheduleLabel;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomToolViewConstraint;
@property (weak, nonatomic) IBOutlet UIButton *gifButton;
@property (strong, nonatomic) IBOutlet CustomSlider *customSlider;

@property (strong, nonatomic)UIView *pointView;
@property (strong, nonatomic)UILabel *pointLabel;

@property (strong, nonatomic)UIImageView *dragImageView;
@end
@implementation VideoCommandView
{
    /** 保存拖动前的视频currentTime */
    CGFloat     _lastCurrentTime;
    /** 视频总时长 */
    int         _totalTime;
    /** 判断是否滑动快进 */
    BOOL        _isShedule;
    NSMutableArray  *_imageArr;
    
}
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        
    }
    return  self;
}

//-(UIView *)sheduleView {
//    if (!_sheduleView) {
//        _sheduleView = [[UIView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH / 2 - 60, (SCREEN_WIDTH * 9 / 16) / 2  - 40, 120, 80)];
//        _sheduleView.backgroundColor = [UIColor blackColor];
//        _sheduleView.alpha = .8;
//        _sheduleView.layer.cornerRadius = 3;
//
//        _sheduleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 40 - 10, 120, 20)];
//        _sheduleLabel.textAlignment = NSTextAlignmentCenter;
//        _sheduleLabel.font = [UIFont systemFontOfSize:14];
//        _sheduleLabel.textColor = [UIColor whiteColor];
//
//        [self addSubview:_sheduleView];
//        [_sheduleView addSubview:_sheduleLabel];
//        _sheduleView.hidden = YES;
//    }
//    return _sheduleView;
//}

- (IBAction)playButton:(UIButton *)sender {
    if (self.commandDelegate && [self.commandDelegate respondsToSelector:@selector(VideoCommandViewPlayButtonClicked)]) {
        sender.selected = [self.commandDelegate VideoCommandViewPlayButtonClicked];
    }
}
- (IBAction)changeFrameButton:(UIButton *)sender {
    
    if (self.commandDelegate && [self.commandDelegate respondsToSelector:@selector(VideoCommandViewChangeFrameButtonClicked)]) {
        [self.commandDelegate VideoCommandViewChangeFrameButtonClicked];
    }
}
/**
 拖动
 */
- (IBAction)sliderValueChanged:(UISlider *)sender {
    if (self.commandDelegate && [self.commandDelegate respondsToSelector:@selector(VideoCommandViewSliderDragingWithTime:)]) {
        [self.commandDelegate VideoCommandViewSliderDragingWithTime:sender.value];
    }
}
/**
 拖动结束
 */
- (IBAction)sliderTouchUpInsideAndOutside:(UISlider *)sender {
    if (self.commandDelegate && [self.commandDelegate respondsToSelector:@selector(VideoCommandViewSliderDragEndWithTime:)]) {
        [self.commandDelegate VideoCommandViewSliderDragEndWithTime:sender.value];
    }
}
- (IBAction)rateButtonClicked:(UIButton *)sender {
    switch (self.rateState) {
        case 0:
        {
            if (self.commandDelegate && [self.commandDelegate respondsToSelector:@selector(VideoCommandViewSetRate:)]) {
                [self.commandDelegate VideoCommandViewSetRate:1];
                self.rateState = normal_rate;
                [self.rateButton setTitle:@"1.0x" forState:UIControlStateNormal];
            }
        }
            break;
        case 1:
        {
            if (self.commandDelegate && [self.commandDelegate respondsToSelector:@selector(VideoCommandViewSetRate:)]) {
                [self.commandDelegate VideoCommandViewSetRate:1.5];
                self.rateState = fast_rate;
                [self.rateButton setTitle:@"1.5x" forState:UIControlStateNormal];
            }
        }
            break;
        case 2:
        {
            if (self.commandDelegate && [self.commandDelegate respondsToSelector:@selector(VideoCommandViewSetRate:)]) {
                [self.commandDelegate VideoCommandViewSetRate:2];
                self.rateState = fastest_rate;
                [self.rateButton setTitle:@"2.0x" forState:UIControlStateNormal];
            }
        }
            break;
        case 3:
        {
            if (self.commandDelegate && [self.commandDelegate respondsToSelector:@selector(VideoCommandViewSetRate:)]) {
                [self.commandDelegate VideoCommandViewSetRate:0.5];
                self.rateState = slow_rate;
                [self.rateButton setTitle:@"0.5x" forState:UIControlStateNormal];
            }
        }
            break;
        default:
            break;
    }
    
}
- (IBAction)screenshotClicked:(UIButton *)sender {
    
    if (self.commandDelegate && [self.commandDelegate respondsToSelector:@selector(VideoCommandViewscreenshotClicked)]) {
        [self.commandDelegate VideoCommandViewscreenshotClicked];
    }
}
- (IBAction)gifClicked:(UIButton *)sender {
    if (self.commandDelegate && [self.commandDelegate respondsToSelector:@selector(VideoCommandViewGifButtonClicked)]) {
        BOOL isGif = [self.commandDelegate VideoCommandViewGifButtonClicked];
        if (isGif) {
            self.gifButton.selected = YES;
        }else{
            self.gifButton.selected = NO;
        }
    }
    
}
#pragma mark    ======== CustomSliderDelegate ========

- (void)CustomSliderPointClicked:(NSInteger *)index WithCenterX:(CGFloat)x{
    if (!self._isFullScreen) {
        return;
    }
    _pointView.frame =CGRectMake(0, self.frame.size.height - 140, 120, 68 + 15);
    
    CGPoint center = self.pointView.center;
    center.x = x;
    self.pointView.center = center;
    self.pointView.hidden = NO;
    
    [self performSelector:@selector(pointViewHidden) withObject:nil afterDelay:3];
}
- (void)pointViewHidden {
    self.pointView.hidden = YES;
}
- (UIImageView *)dragImageView {
    if (!_dragImageView) {
        _dragImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, self.frame.size.height - 140, 120, 68)];
        _dragImageView.layer.borderColor = [UIColor whiteColor].CGColor;
        _dragImageView.layer.borderWidth = 1;
        
        _dragImageView.hidden = YES;
        [self addSubview:_dragImageView];
    }
    return _dragImageView;
}
- (void)CustomSliderDraging:(CustomSlider *)sender {
    if (!self._isFullScreen) {
        return;
    }
    if (self.commandDelegate && [self.commandDelegate respondsToSelector:@selector(VideoCommandViewSliderDragingWithTime:)]) {
        [self.commandDelegate VideoCommandViewSliderDragingWithTime:sender.value];
    }

    CGPoint center = self.dragImageView.center;
    center.x = sender.dragX;
    _dragImageView.center = center;
    
    float x = sender.dragX - 100;
    float max = self.bounds.size.width - 200;
    int number = max / _imageArr.count;
    int index = x / number;
    
    if (index <= _imageArr.count-1) {
        _dragImageView.image = _imageArr[index];
    }
    
    _dragImageView.hidden = NO;
    
}
- (void)dragImageViewHidden {
    _dragImageView.hidden = YES;
}
- (void)CustomSliderDragingEnd:(CustomSlider *)sender {
    if (self._isFullScreen) {
        [self performSelector:@selector(dragImageViewHidden) withObject:nil afterDelay:.5];

    }
    if (self.commandDelegate && [self.commandDelegate respondsToSelector:@selector(VideoCommandViewSliderDragEndWithTime:)]) {
        [self.commandDelegate VideoCommandViewSliderDragEndWithTime:sender.value];
    }
}
- (UIView *)pointView {
    if (!_pointView) {
        _pointView = [[UIView alloc]initWithFrame:CGRectMake(0, self.frame.size.height - 140, 120, 68 + 15)];
        _pointView.backgroundColor = [UIColor blackColor];
        
        _pointLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 68, 120, 20)];
        _pointLabel.textAlignment =  NSTextAlignmentCenter;
        _pointLabel.textColor = [UIColor whiteColor];
        _pointLabel.text = @"这里是热点提示！";
        _pointLabel.font = [UIFont systemFontOfSize:9];
        _pointLabel.numberOfLines = 2;
        
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 120, 68)];
        imageView.image = [UIImage imageNamed:@"002.jpg"];
        [_pointView addSubview:imageView];
        imageView.layer.borderWidth = 1;
        imageView.layer.borderColor = [UIColor whiteColor].CGColor;
        
        
        [_pointView addSubview:_pointLabel];
        [self addSubview:_pointView];
        _pointView.hidden = YES;
        
    }
    return _pointView;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
}
- (void)setGifButtonSelectState:(BOOL)selected {
    if (selected) {
        self.gifButton.selected = YES;
    }else{
        self.gifButton.selected = NO;
    }
    
}
- (void)awakeFromNib {
    [super awakeFromNib];
   // self.safeAreaLayoutGuide
    
    
    _imageArr = [NSMutableArray array];
    for (int i = 0; i < 14 ; i++) {
        int x = i+ 111;
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%d.jpg",x]];
        [_imageArr addObject:image];
    }
    
    [self sheduleView];
    [self.playButton setTitle:@"play" forState:UIControlStateNormal];
    [self.playButton setTitle:@"pause" forState:UIControlStateSelected];
    self.rateState = normal_rate;
    [self.videoSlider setThumbImage:[UIImage imageNamed:@"voice_slide"] forState:UIControlStateNormal];
//    [self.videoSlider setMinimumTrackImage:[self imageWithColor:[UIColor yellowColor]] forState:UIControlStateNormal];
//    [self.videoSlider setMaximumTrackImage:[self imageWithColor:[UIColor redColor]] forState:UIControlStateNormal];
    self.customSlider.delegate = self;
    
    
    
    // 使用方法二 全代码使用
    BrightnessVolumeView *brightnessVolumeView = [[BrightnessVolumeView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height - 44)];
    brightnessVolumeView.brightnessDelegate = self;
    
    [self insertSubview:brightnessVolumeView atIndex:0];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(nothing)];
    [self.bottomToolView addGestureRecognizer:tap];
    
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(setToolViewHidden)];
    [self addGestureRecognizer:tap1];
    
    _sheduleView.alpha = .8;
    _sheduleView.layer.cornerRadius = 3;
    _sheduleView.hidden = YES;
    
    _sheduleLabel.textAlignment = NSTextAlignmentCenter;
    _sheduleLabel.font = [UIFont systemFontOfSize:14];
    _sheduleLabel.textColor = [UIColor whiteColor];
    self.layer.masksToBounds = YES;
    
    self.rightToolView.hidden = YES;
}
- (void)setToolViewHidden {
    if (_topToolView.hidden) {
        self.bottomToolViewConstraint.constant += 60;
        [UIView animateWithDuration:0.65 animations:^{
            [self layoutIfNeeded];
        }];
        [self setCommandToolViewHidden:NO];
    }else{
        self.bottomToolViewConstraint.constant -= 60;
        [UIView animateWithDuration:0.65 animations:^{
            [self layoutIfNeeded];
        }];
        [self setCommandToolViewHidden:YES];
    }
}
- (void)set_isFullScreen:(BOOL)_isFullScreen {
    __isFullScreen = _isFullScreen;
    if (_isFullScreen) {
        self.rightToolView.hidden = NO;
    }else{
        self.rightToolView.hidden = YES;
    }
}
- (void)nothing {
    
}

/**
 更新slider和label值
 */
- (void)refreshSliderValueWithTime:(CGFloat )time {
    NSInteger intCurrentTimeValue = round(time);
    self.currentTimeLabel.text = [NSString stringWithFormat:@"%.2d:%.2d",(int)(intCurrentTimeValue/60),(int)(intCurrentTimeValue%60)];
    self.videoSlider.value = time;
    self.customSlider.value = time;
    if (!_isShedule) {
        _lastCurrentTime = time;
    }
    
}
/**
 赋值slider和视频总时长
 */
- (void)setVideoTotalTime:(CGFloat )time {
    if (time < 0) {
        self.totalTimeLabel.text = @"--:--";
        self.currentTimeLabel.text = @"--:--";
    }else{
        NSInteger intDuration = round(time);
        self.totalTimeLabel.text = [NSString stringWithFormat:@"%.2d:%.2d",(int)(intDuration/60),(int)(intDuration%60)];
        self.videoSlider.maximumValue = time;
        self.customSlider.maximumValue = time;
        _totalTime = intDuration;
    }
    
}

- (void)setPointWithSlider:(NSArray *)array {
    NSArray *arr = [NSArray arrayWithObjects:[NSNumber numberWithFloat:2], [NSNumber numberWithFloat:5],[NSNumber numberWithFloat:10],[NSNumber numberWithFloat:11],nil];
    self.customSlider.pointArray = arr;
}
/**
 显示隐藏ToolView
 */
- (void)setCommandToolViewHidden:(BOOL )hidden {
    //self.bottomToolView.hidden = hidden;
    if (!self._isFullScreen ) {
        self.rightToolView.hidden = YES;
    }else{
        self.rightToolView.hidden = hidden;
    }
    
    self.topToolView.hidden = hidden;
}
/**
 播放按钮
 */
- (void)setPlayButtonState:(BOOL )isPlaying{
    self.playButton.selected = isPlaying;
}
/**
 更换视频后还原属性:现在为速率值还原为1
 */
- (void)forNewVideo{
    self.rateState = normal_rate;
    [self.rateButton setTitle:@"1.0x" forState:UIControlStateNormal];
}





#pragma mark    ======== BrightnessViewDelegate ========
- (void)BrightnessViewsSheduleForVideo:(CGFloat)time {
    _isShedule = YES;
    _sheduleView.hidden = NO;
    int shedulTime = _lastCurrentTime + time;
    if (shedulTime < 0) {
        shedulTime = 0;
    }
    if (shedulTime > _totalTime) {
        shedulTime = _totalTime;
    }
    NSString *sheduleTimeStr = [NSString stringWithFormat:@"%.2d:%.2d",(int)(shedulTime/60),(int)(shedulTime%60)];
    _sheduleLabel.text = [NSString stringWithFormat:@"%@/%@",sheduleTimeStr,self.totalTimeLabel.text];
}
- (void)BrightnessViewsSheduleEndForVideo:(CGFloat)time {
    int shedulTime = _lastCurrentTime + time;
    if (shedulTime < 0) {
        shedulTime = 0;
    }
    if (shedulTime > _totalTime) {
        shedulTime = _totalTime;
    }
    if (self.commandDelegate && [self.commandDelegate respondsToSelector:@selector(VideoCommandViewWithVideoTime:)]) {
        [self.commandDelegate VideoCommandViewWithVideoTime:shedulTime];
    }
    _sheduleView.hidden = YES;
    _isShedule = NO;
}


- (UIImage *)imageWithColor:(UIColor *)color//
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
